<!--
 * @Author: 赵克强 huohuo625@163.com
 * @Date: 2023-10-17 10:13:29
 * @LastEditors: 赵克强 huohuo625@163.com
 * @LastEditTime: 2025-01-22 10:15:23
 * @FilePath: \hy-ui\src\plugins\package\penal\base\ElementBaseInfo.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="panel-tab__content">
    <el-form size="mini" label-width="90px" @submit.native.prevent>
      <el-form-item label="ID">
        <el-input v-model="elementBaseInfo.id" :disabled="idEditDisabled || elementBaseInfo.$type === 'bpmn:Process'"
          clearable @change="updateBaseInfo('id')" />
      </el-form-item>
      <el-form-item label="名称">
        <el-input v-model="elementBaseInfo.name" clearable @change="updateBaseInfo('name')" />
      </el-form-item>

      <!-- <el-form-item label="抄送流程"  v-if="type === 'UserTask'">
        <el-switch
          v-model="elementBaseInfo.makeACopyFor"
          active-text="是"
          inactive-text="否"
          @change="(val)=>updateBaseInfo('makeACopyFor',val)"
        />
      </el-form-item> -->
      <!--流程的基础属性-->
      <template v-if="elementBaseInfo.$type === 'bpmn:Process'">
        <el-form-item label="表单">
          <el-select v-model="elementBaseInfo.formCode" placeholder="请选择表单" @change="updateBaseInfo('formCode')">
            <el-option v-for="item in formOptions" :key="item.formId" :label="item.formName"
              :value="`key_${item.formId}`" />
          </el-select>
        </el-form-item>
        <el-form-item label="标题字段" prop="processTitle">
          <el-input :placeholder="elementBaseInfo.formCode ? '标题字段' : '请先选择表单'
            " :disabled="!elementBaseInfo.formCode" type="textarea" :rows="3" v-model="titleFieldLabel"
            @focus="handleOpenTitleFieldSetting">
          </el-input>
        </el-form-item>
        <el-form-item label="版本标签">
          <el-input v-model="elementBaseInfo.versionTag" clearable @change="updateBaseInfo('versionTag')" />
        </el-form-item>
        <el-form-item label="可执行">
          <el-switch v-model="elementBaseInfo.isExecutable" active-text="是" inactive-text="否"
            @change="(val) => updateBaseInfo('isExecutable', val)" />
        </el-form-item>
      </template>
    </el-form>
    <el-dialog title="标题设置" :visible.sync="titleSettingOpen" width="40%" v-if="titleSettingOpen"
      :before-close="() => (titleSettingOpen = false)" append-to-body destroy-on-close custom-class="titleSetting">
      <div>
        <el-input readonly type="textarea" :rows="3" placeholder="请选择" v-model="titleFieldLabel" />
        <div style="display: flex; margin-top: 12px">
          <div style="flex: 1; margin-right: 60px">
            <div style="margin-bottom: 12px">
              表单字段<el-button type="primary" @click="addStaticText" size="mini"
                style="margin-left: 12px">添加静态文字</el-button>
            </div>
            <div style="
                border-radius: 4px;
                border: 1px solid #d7dae2;
                height: 400px;
                overflow-y: scroll;
              ">
              <div :class="[
                'fieldTitleItem',
                titleFieldValue.includes(item.options.name)
                  ? 'selected'
                  : null,
              ]" style="
                  display: flex;
                  justify-content: space-between;
                  align-items: center;
                " v-for="item in feildList" :key="item.options.name" @click="handleTitleFieldChange(item, 'form')">
                <span>{{ item.options.label }}</span><i @click.stop="handleDeleteField(item)" class="el-icon-delete-solid"
                  style="color: red" v-if="item.type === 'text'"></i>
              </div>
            </div>
          </div>
          <div style="flex: 1">
            <div style="margin-bottom: 12px">系统字段</div>
            <div style="
                border-radius: 4px;
                border: 1px solid #d7dae2;
                height: 400px;
                overflow-y: scroll;
              ">
              <div :class="[
                'fieldTitleItem',
                titleFieldValue.includes(item.options.name)
                  ? 'selected'
                  : null,
              ]" v-for="item in titleFieldSysList" :key="item.options.name"
                @click="handleTitleFieldChange(item, 'sys')">
                {{ item.options.label }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  listForm,
  saveAppProcessTitleFormField,
  getAppProcessTitleFormField,
} from "@/api/workflow/form";
export default {
  name: "ElementBaseInfo",
  props: {
    businessObject: Object,
    type: String,
    elementType: String,
    appId: String,
    getTitleField: Function,
    setTableName: Function,
    idEditDisabled: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      elementBaseInfo: {},
      formOptions: [],
      titleSettingOpen: false,
      titleField: [],
      titleFieldValue: [],
      titleFieldLabel: undefined,
      feildList: [],
      titleFieldSysList: [],
      titleFieldOption: [],
    };
  },
  watch: {
    businessObject: {
      immediate: false,
      handler: function (val) {
        if (val) {
          this.$nextTick(() => this.resetBaseInfo());
        }
      },
    },
  },
  methods: {
    async initFormFields() {
      const data = this.formOptions.filter(
        (item) => `key_${item.formId}` === `${window.bpmnInstances.bpmnElement.businessObject?.$parent
          ?.formCode || window.bpmnInstances.bpmnElement.businessObject
            ?.formCode}`
      );
      let widgetList = undefined;
      if (data.length && data[0]?.widgetList) {
        widgetList = JSON.parse(data[0]?.widgetList);
      }

      return widgetList
    },
    async handleDeleteField(val) {
      this.feildList = this.feildList.filter(
        (item) => item.options.name !== val.options.name
      );
      this.titleField = this.titleField.filter(
        (item) => item.options.name !== val.options.name
      );
      this.titleFieldValue = this.titleFieldValue.filter(
        (item) => item !== val.options.name
      );
      this.titleFieldLabel = "";
      this.titleField.forEach((item, index) => {
        if (index + 1 !== this.titleField.length) {
          this.titleFieldLabel += `${item.options.label}-`;
        } else {
          this.titleFieldLabel += item.options.label;
        }
      });
      await saveAppProcessTitleFormField({
        processKey: this.elementBaseInfo.id,
        titleField: JSON.stringify(this.feildList),
      });
    },
    addStaticText() {
      this.$prompt("确认添加吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "info",
        inputPlaceholder: "请输入",
        inputType: "input",
      }).then(async ({ value }) => {
        this.feildList.unshift({
          type: "text",
          options: { label: value, name: value },
        });
        await saveAppProcessTitleFormField({
          processKey: this.elementBaseInfo.id,
          titleField: JSON.stringify(this.feildList),
        });
      });
    },
    handleTitleFieldChange(val, type) {
      this.titleFieldLabel = "";
      if (this.titleFieldValue.includes(val.options.name)) {
        this.titleField = this.titleField.filter(
          (item) => item.options.name !== val.options.name
        );
        this.titleFieldValue = this.titleFieldValue.filter(
          (item) => item !== val.options.name
        );
      } else {
        this.titleField.push({ ...val, titleFieldType: type });
        this.titleFieldValue.push(val.options.name);
      }
      this.titleField.forEach((item, index) => {
        if (index + 1 !== this.titleField.length) {
          this.titleFieldLabel += `${item.options.label}-`;
        } else {
          this.titleFieldLabel += item.options.label;
        }
      });
    },
    extractDeepestWidgetList(val) {
      val.forEach((item) => {
        if (item.category !== "container" && item.merged !== false) {
          this.titleFieldOption.push(item);
        } else {
          for (let i in item) {
            if (Object.prototype.toString.call(item[i]) === "[object Array]") {
              this.extractDeepestWidgetList(item[i]);
            }
          }
        }
      });
    },
    async handleOpenTitleFieldSetting() {
      const res = await getAppProcessTitleFormField({
        processKey: this.elementBaseInfo.id,
      });
      if (!res.rows?.length || !res.rows?.[0]?.titleField) {
        const data = this.formOptions.filter(
          (item) => `key_${item.formId}` === `${this.elementBaseInfo.formCode}`
        );
        let widgetList = undefined;
        this.titleFieldOption = [];
        if (data.length && data[0]?.widgetList) {
          widgetList = JSON.parse(data[0]?.widgetList);
          this.extractDeepestWidgetList(widgetList);
          let filterCom = [
            "static-title",
            "date-range",
            "switch",
            "rate",
            "color",
            "slider",
            "static-title",
            "html-text",
            "button",
            "divider",
            "static-input",
            "node-approver",
            "table-children",
            "table-children-relation",
            "dept-change-post",
            "popup-selection",
            "treeSelect",
            "picture-upload",
            "file-upload",
            "rich-editor",
            "cascader",
            "custom-select",
            "slice-upload"
          ];
          const arr = [];
          this.titleFieldOption.forEach((item) => {
            if (!filterCom.includes(item.type) && item.options.label) {
              arr.push(item);
            }
          });
          arr.forEach((item) => {
            if (
              item.options?.dictType &&
              !item.options?.dictUrl &&
              item.options.optionItems?.length
            ) {
              item.options.dictUrl = item.options.optionItems[0]?.dictType;
            }
          });
          arr.push({
            type: "createBy",
            options: { label: "发起人", name: "createBy" },
          });
          this.feildList = arr;
        }
        await saveAppProcessTitleFormField({
          processKey: this.elementBaseInfo.id,
          titleField: JSON.stringify(this.feildList),
        });
      } else {
        this.feildList = res.rows[0]?.titleField
          ? JSON.parse(res.rows[0]?.titleField)
          : [];
      }
      this.titleSettingOpen = true;
    },
    async resetBaseInfo() {
      this.bpmnElement = window?.bpmnInstances?.bpmnElement;
      this.elementBaseInfo = {
        ...this.elementBaseInfo,
        ...JSON.parse(JSON.stringify(this.bpmnElement.businessObject)),
        formCode: this.bpmnElement.businessObject?.formCode,
      };
      if (this.type === "Task") {
        this.elementBaseInfo.name = this.elementBaseInfo.name
          ? this.elementBaseInfo.name
          : "抄送节点";
      }
      const response = await listForm({
        appId: this.appId,
      });
      this.formOptions = response.rows;
      const result = this.formOptions?.filter(
        (item) => `key_${item.formId}` === this.elementBaseInfo.formCode
      );
      if (result.length) {
        this.setTableName(result?.[0]?.tableName);
      }
      const res = await this.getTitleField(this.elementBaseInfo.id);
      this.titleField = this.titleField && this.titleField?.length ? this.titleField : res.titleField;
      this.titleFieldValue = this.titleFieldValue && this.titleFieldValue?.length ? this.titleFieldValue : res.titleFieldValue;
      this.titleFieldLabel = this.titleFieldLabel ? this.titleFieldLabel : res.titleFieldLabel;
    },
    async updateBaseInfo(key) {
      const attrObj = Object.create(null);
      attrObj[key] = this.elementBaseInfo[key];
      if (key === "id") {
        window.bpmnInstances.modeling.updateProperties(this.bpmnElement, {
          id: this.elementBaseInfo[key],
          di: { id: `${this.elementBaseInfo[key]}_di` },
        });
      } else {
        window.bpmnInstances.modeling.updateProperties(
          this.bpmnElement,
          attrObj
        );
      }
      if (key === "formCode") {
        const result = this.formOptions?.filter(
          (item) => `key_${item.formId}` === this.elementBaseInfo.formCode
        );
        if (result.length) {
          this.setTableName(result?.[0]?.tableName);
        }
        await saveAppProcessTitleFormField({
          processKey: this.elementBaseInfo.id,
          titleField: "",
        });
        this.titleField = [];
        this.titleFieldValue = [];
        this.titleFieldLabel = undefined;
      }
    },
  },
  beforeDestroy() {
    this.bpmnElement = null;
  },
};
</script>

<style lang="scss" scoped>
::v-deep .titleSetting {
  .el-dialog__body {
    // height: 70vh;
  }

  .fieldTitleItem {
    line-height: 34px;
    height: 34px;
    color: #606266;
    font-size: 14px;
    padding: 0 20px;
    cursor: pointer;
  }

  .fieldTitleItem:hover {
    background-color: #f5f7fa;
  }

  .fieldTitleItem.selected {
    color: #409eff;
    font-weight: 700;
  }
}
</style>
